package com.shujia.wyh.day11;


import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

/*
    "aababcabcdabcde",获取字符串中每一个字母出现的次数要求结果:a(5)b(4)c(3)d(2)e(1)
 */
public class MapTest2 {
    public static void main(String[] args) {
        //定义一个字符串
        String s = "aababcabcdabcde";

        //将字符串转成字符数组
        char[] chars = s.toCharArray();

        //创建一个TreeMap
        TreeMap<Character, Integer> map = new TreeMap<>();

        //遍历数组得到每一个字符
        for (char c : chars) {
            //判断集合中是否存在该字符为key
            if (map.containsKey(c)) {
                //如果key存在，将key对应的value值取出来+1，再赋值回去
                Integer count = map.get(c);
                map.put(c, count + 1);
            } else {
                map.put(c, 1);
            }
        }

        //创建一个StringBuilder
        StringBuilder stringBuilder = new StringBuilder();

        Set<Map.Entry<Character, Integer>> entries = map.entrySet();
        for (Map.Entry<Character, Integer> entry : entries) {
            Character key = entry.getKey();
            Integer value = entry.getValue();
            stringBuilder.append(key).append("(").append(value).append(")");
        }

        //将StringBuilder转成字符串输出
        String result = stringBuilder.toString();
        System.out.println(result);

    }
}
